#include "delay.h"

static uint8_t  fac_us=0;
static uint16_t fac_ms=0;
void Delay_Init(uint8_t SYSCLK)
{
  SysTick->CTRL&=~(1<<2);
  fac_us=SYSCLK/8;
  fac_ms=((uint32_t)SYSCLK*1000)/8;
}
void delay_xms(uint16_t nms)
{
  uint32_t temp;
  SysTick->LOAD=(uint32_t)nms*fac_ms;
  SysTick->VAL =0x00;
  SysTick->CTRL=0x01 ;
  do
  {
    temp=SysTick->CTRL;
  }while((temp&0x01)&&!(temp&(1<<16)));
  SysTick->CTRL=0x00;
  SysTick->VAL =0X00;
}

void Delay_MS(uint16_t nms)
{
  uint8_t repeat=nms/540;
  uint16_t remain=nms%540;
  while(repeat)
  {
    delay_xms(540);
    repeat--;
  }
  if(remain)delay_xms(remain);

}
void Delay_US(uint32_t nus)
{
  uint32_t temp;
  SysTick->LOAD=nus*fac_us;
  SysTick->VAL=0x00;
  SysTick->CTRL=0x01 ;
  do
  {
    temp=SysTick->CTRL;
  }while((temp&0x01)&&!(temp&(1<<16)));
  SysTick->CTRL=0x00;
  SysTick->VAL =0X00;
}
